using System;
using System.IO;
using System.Reflection;
using EsbMonitorMessages;
using NServiceBus;
using NServiceBus.Unicast;

namespace TestHost
{
    public class ClientEndpoint : IWantToRunAtStartup
    {
        public IBus Bus { get; set; }

        #region IWantToRunAtStartup Members

        public void Run()
        {
            Console.WriteLine("Press 'Enter' to send a message.To exit, Ctrl + C");
            Guid guid = Guid.NewGuid();
            while (Console.ReadLine() != null)
            {
                Guid g = Guid.NewGuid();

                Console.WriteLine("Requesting to get data by id: {0}", g.ToString("N"));

                var unicastBus = (UnicastBus) Bus;
                unicastBus.ClientSubscribed += (sender, e) => Console.WriteLine("Koles sie zasubskrybowal");

                foreach (String messageOwner in unicastBus.MessageOwners.Keys)
                {
                    if (!messageOwner.StartsWith("NServiceBus"))
                    {
                        Assembly a = Assembly.Load(messageOwner);
                            SendMessageAssemblyInfo(a);
                    }
                }

                
//
//                Bus.Send<IPublisherStartedEvent>(m =>
//                                                {
//                                                    m.EventId = Guid.NewGuid();
//                                                    m.Guid = guid;
//                                                    m.Name = "Michal";
//                                                    m.Time = DateTime.Now;
//                                                    m.InputQueueName = "loage";
//                                                });
            }
        }

        public void Stop()
        {
        }

        #endregion

        private void SendMessageAssemblyInfo(Assembly assembly)
        {
            string fullName = assembly.FullName;
            string location = assembly.Location;
            string fileName = assembly.ManifestModule.ScopeName;
            Guid moduleVersionId = assembly.ManifestModule.ModuleVersionId;

            byte[] binaryData = File.ReadAllBytes(location);

            Bus.Send<IMessageAssemblyLoadedEvent>(m =>
                                                      {
                                                          m.FileName = fileName;
                                                          m.FullName = fullName;
                                                          m.ModuleVersionId = moduleVersionId;
                                                          m.BinaryData = binaryData;
                                                      }
                );
        }
    }
}